package edu.hrbu.redis02.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.hrbu.redis02.entity.Goods;
import edu.hrbu.redis02.entity.O;
import edu.hrbu.redis02.mapper.OrderMapper;
import edu.hrbu.redis02.service.GoodsService;
import edu.hrbu.redis02.service.OrderService;
import edu.hrbu.redis02.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author 徐登宇
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, O> implements OrderService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private GoodsService goodsService;

    // 缓存中的订单写进数据库
    @Override
    public R rollback(String goodsKey, String count) {
        int c = 0;
        if (!ObjectUtils.isEmpty(count)) {
            c = Integer.parseInt(count);
        }
        Goods goods = goodsService.getById(Integer.valueOf(goodsKey));
        goods.setGoodsCount(goods.getGoodsCount() + c);
        // 剩余商品写回数据库
        goodsService.update(goods, null);
        // 订单写进order
        // 数组json
        List<String> orderArrJson = stringRedisTemplate.opsForList().range(goods.getGoodsId().toString(), 0, -1);
//        log.error("@@ "+orderArrJson);
        for (String e : orderArrJson) {
            log.debug(e);
            // 将缓存订单数据反序列化为O【没有oid】
            O o = JSONUtil.toBean(e, O.class);
            LambdaQueryWrapper<O> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(O::getUserId, o.getUserId())
                    .eq(O::getGoodsId, o.getGoodsId());
            O one = getOne(queryWrapper);
            if (ObjectUtils.isEmpty(one)) save(o);
//            System.out.println(o);
            else {
                one.setGoodsCount(one.getGoodsCount() + o.getGoodsCount());
                update(one, new LambdaUpdateWrapper<O>()
                        .eq(O::getUserId, o.getUserId())
                        .eq(O::getGoodsId, o.getGoodsId()));
            }
        }
        // 订单写入完成后，清空订单缓存
        stringRedisTemplate.delete(goods.getGoodsId().toString());

        return R.ok("生成订单："+orderArrJson);
    }
}
